/*
    订单管理:商城购买订单
 */
$(function () {
    let shippingStatus = getQueryString("shippingStatus");
    let payStatus = getQueryString("payStatus");
    let orderStatus = getQueryString("orderStatus");
    let orderType = getQueryString("orderType");
    let type = 1;
    let url = '../order/list';
    if (shippingStatus) {
        url += '?shippingStatus=' + shippingStatus;
    }
    if (payStatus) {
        url += '?payStatus=' + payStatus;
    }
    if (orderStatus) {
        url += '?orderStatus=' + orderStatus;
    }
    $("#jqGrid").Grid({
        url: url,
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '订单号', name: 'orderNo', index: 'orderNo', width: 110},
            {label: '用户编号', name: 'userId', index: 'userId', width: 50},
            {label: '商户名', name: 'merchantName', index: 'merchantName', width: 50},
            {label: '手机号', name: 'userPhone', index: 'userPhone', width: 50},
            {label: '产品名称', name: 'productName', index: 'productName', width: 50},
            {label: '订单金额', name: 'amount', index: 'amount', width: 50},
            {label: '服务费', name: 'rateValue', index: 'rateValue', width: 50},
            {label: '实付', name: 'realAmount', index: 'realAmount', width: 50},
            {label: '实收金额', name: '', index: '', width: 50,
                formatter:function (cellvalue, options, row) {
                    return (row.amount - row.rateValue);}
            },
            {label: '收货人', name: 'receiveUser', index: 'receiveUser', width: 50},
            {label: '收货人手机', name: 'receivePhone', index: 'receivePhone', width: 50},
            {label: '数量', name: 'number', index: 'number', width: 50},
            {
                label: '订单状态', name: 'status', index: 'status', width: 60,
                formatter: function (value) {
                    if (value == '1') {
                        return '未支付';
                    } else if (value == '2') {
                        return '支付完成';
                    } else if (value == '3') {
                        return '已取消';
                    } else if (value == '4') {
                        return '已完成';
                    } else if (value == '5') {
                        return '待发货';
                    } else if (value == '6') {
                        return '已发货';
                    } else if (value == '9') {
                        return '退款处理';
                    } else if (value == '10') {
                        return '退款中';
                    } else if (value == '11') {
                        return '退款完成';
                    }
                    return value;
                }
            },
            {
                label: '付款状态', name: 'payStatus', index: 'payStatus', width: 60,
                formatter: function (value) {
                    if (value == '0') {
                        return '未付款';
                    } else if (value == '1') {
                        return '付款中';
                    } else if (value == '2') {
                        return '已付款';
                    }
                    return value;
                }
            },
            {label: '付款方式', name: 'payWay', index: 'payWay', width: 80,
                formatter: function (value) {
                    if (value == '1') {
                        return '微信支付';
                    } else if (value == '2') {
                        return '支付宝';
                    }
                    return value;
                }
            },
            {label: '地址', name: 'addressStr', index: 'addressStr', width: 80},
            {label: '物流单号', name: 'logisticsno', index: 'logisticsno', width: 80},
            {label: '备注', name: 'remark', index: 'remark', width: 80},
            {
                label: '下单时间', name: 'createDate', index: 'createDate', width: 80,
                formatter: function (value) {
                    return transDate(value);
                }
            },
            {label: '支付时间', name: 'payDate', index: 'payDate', width: 60}
        ]
    });
    $("#ordergoodsGrid").Grid({
        datatype: "local",
        multiselect: false,
        height: 'auto',
        colModel: [
            {label: 'productId', name: 'productId', index: 'productId', key: true, hidden: true},
            {label: '商品规格', name: 'goodsSpecifitionNameValue', index: 'goodsSpecifitionNameValue', width: 500},
            {label: '商品单价', name: 'retailPrice', index: 'retailPrice', width: 80},
            {label: '商品数量', name: 'number', index: 'number', width: 60}
            // {
            //     label: '操作', width: 80, align: 'center', sortable: false, formatter: function (value, col, row) {
            //         var str = '<button class="btn btn-outline btn-info" onclick="vm.deleteOrdergoods(' + row.productId + ')"><i class="fa fa-info-circle"></i>&nbsp;删除</button>';
            //         return str;
            //     }
            // }
        ]
    });
    // let url1 = '../ordergoods/list?orderId=1';
    // $("#ordergoodsLookGrid").Grid({
    //     url: url1,
    //     datatype: "json",
    //     multiselect: false,
    //     height: 'auto',
    //     colModel: [
    //         {label: 'productId', name: 'productId', index: 'productId', key: true, hidden: true},
    //         {label: '商品规格', name: 'goodsSpecifitionNameValue', index: 'goodsSpecifitionNameValue', width: 500},
    //         {label: '商品单价', name: 'retailPrice', index: 'retailPrice', width: 80},
    //         {label: '商品数量', name: 'number', index: 'number', width: 60}
    //     ]
    // });
    // let url2 = '../ordergoods/list?orderId=1';
    // $("#ordergoodsLookConfirmGrid").Grid({
    //     url: url2,
    //     datatype: "json",
    //     multiselect: false,
    //     height: 'auto',
    //     colModel: [
    //         {label: 'productId', name: 'productId', index: 'productId', key: true, hidden: true},
    //         {label: '商品规格', name: 'goodsSpecifitionNameValue', index: 'goodsSpecifitionNameValue', width: 500},
    //         {label: '商品单价', name: 'retailPrice', index: 'retailPrice', width: 80},
    //         {label: '商品数量', name: 'number', index: 'number', width: 60}
    //     ]
    // });
    Ajax.request({
        url: "../sys/merchant/queryMerchant",
        async: true,
        successCallback: function (r) {
            vm.merchants = [];
            vm.merchants = r.list;
        }
    });
});
let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        detail: false,
        showadd: false,
        showconfirm: false,
        showupdate: false,
        showselect: false,
        ddd: true,
        title: null,
        retailPrice: 0,
        order: {
            shippingFee: 0,
            //订单状态
            orderStatus: 0,
            //发货状态
            shippingStatus: 0,
            //付款状态
            payStatus: 0,
            shippingId: 0,
            integral: 0,
            integralMoney: 0,
            freightPrice: 0,
            couponPrice: 0,
            iscomment: 0,
            logisticsno: 0,
            productName: 0,
            start:'',
            end:''
        },
        logistics: {},
        user: {},
        goodss: [],
        products: [],
        ordergoodss: [],
        goodsproducts: [],
        userphone: null,
        shippings: [],
        merchants:[],
        userName: '',
        retailPrice: 0,
        noandname: '',
        ordergoods: {
            goodsname: '',
            goodsid: 0,
            number: 1
        },
        q: {
            orderNo: '',
            userPhone: '',
            payStatus: '',
            status: '',
            payWay:'',
            date:'',
            merchantId:''
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },

        exportPro: function () {
            var strhref = "../order/export?status=" + vm.q.status;
            if (vm.q.userPhone != '')
                strhref += "&userPhone=" + vm.q.userPhone;
            if (vm.q.payStatus != '')
                strhref += "&payStatus=" + vm.q.payStatus;
            if (vm.q.orderNo != '')
                strhref += "&orderNo=" + vm.q.orderNo;
            if (vm.q.payWay != '')
                strhref += "&payWay=" + vm.q.payWay;
            if(vm.q.merchantId != ''){
                strhref += "&merchantId="+vm.q.merchantId;
            }
            let index = $("#jqGrid").jqGrid('getGridParam', 'page');
            strhref += "&index=" + index;
            strhref += "&size=" + 50;
            location.href = strhref;
        },
        select: function (event) {
            vm.showList = false;
            vm.detail = false;
            vm.showconfirm = false;
            vm.showadd = false;
            vm.showupdate = false;
            vm.showselect = true;
            vm.title = "查看";
            let ids = getSelectedRow("#jqGrid");
            if (ids == null) {
                return;
            }
            Ajax.request({
                url: "../order/info/" + ids,
                async: true,
                successCallback: function (r) {
                    vm.order = r.order;

                }
            });

        },
        openDetail:function(){
            let ids = getSelectedRow("#jqGrid");
            if (ids == null) {
                return;
            }
            Ajax.request({
                url: "../order/info/" + ids,
                async: false,
                successCallback: function (r) {
                    vm.order = r.order;
                }
            });
            vm.openSpe(vm.order.orderNo)
        },
        openSpe: function (orderNo) {
            openWindow({
                type: 2,
                area: ['1000px', '600px'],
                title: '订单详情',
                content: 'orderdetail.html?orderNo='+orderNo,
                btn: ['确定', '取消'],
                btn1: function (index) {
                    layer.close(index);
                }
            })
        },
        update: function (event) {
            let ids = getSelectedRow("#jqGrid");
            if (ids == null) {
                return;
            }
            vm.showList = false;
            vm.detail = false;
            vm.showconfirm = false;
            vm.showadd = true;
            vm.showupdate = true;
            vm.title = "修改";
            Ajax.request({
                url: "../order/info/" + ids,
                async: true,
                successCallback: function (r) {
                    vm.order = r.order;
                }
            });

        },
        add: function () {
            vm.showList = false;
            vm.detail = false;
            vm.showconfirm = false;
            vm.showadd = true;
            vm.title = "新增";
            vm.ordergoodss = [];
            vm.products = [];
            vm.userphone = null;
            $("#ordergoodsGrid").jqGrid("clearGridData");
            vm.logistics = {};
            vm.user = {};
            vm.userName = '';
            vm.retailPrice = '';
            vm.noandname = '';
            vm.ordergoods = {
                retailPrice: 0,
                goodsname: '',
                goodsid: 0,
                number: 1
            },
                vm.order = {
                    orderPrice: 0,
                    goodsPrice: 0,
                    actualPrice: 0,
                    shippingFee: 0,
                    //订单状态
                    orderStatus: 0,
                    //发货状态
                    shippingStatus: 0,
                    //付款状态
                    payStatus: 0,
                    shippingId: 0,
                    integral: 0,
                    integralMoney: 0,
                    freightPrice: 0,
                    couponPrice: 0,
                    iscomment: 0
                };

            const now = new Date();
            var month = now.getMonth() + 1;
            var day = now.getDate();
            var hour = now.getHours();
            var minutes = now.getMinutes();
            var seconds = now.getSeconds();

            vm.order.orderSn = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 89 + 100)).toString()
            vm.ordergoods.orderNo = vm.order.orderSn;


            //this.getGoodss();
        },
        //搜索用户
        searchuser: function () {
            if (vm.userphone == null)
                alert("请输入用户手机号");
            Ajax.request({
                url: "../user/infobyphone/" + vm.userphone,
                async: true,
                successCallback: function (r) {
                    if (r.user == null) {
                        alert("该会员不存在");
                    }
                    vm.user = r.user;
                    vm.order.userId = r.user.id;
                    vm.userName = r.user.username;
                }
            });
        },
        //搜索商品
        searchgoods: function () {
            if (vm.noandname == null)
                alert("请输入商品编号或者名称");
            Ajax.request({
                url: "../goods/infobynoandname/" + vm.noandname,
                async: true,
                successCallback: function (r) {
                    if (r.goods == null) {
                        alert("该商品不存在");
                    }
                    /*   vm.order.actualPrice =  parseFloat(vm.order.shippingFee);
                       vm.order.orderPrice = parseFloat(r.goods.retailPrice) * parseFloat(vm.ordergoods.number) + parseFloat(vm.order.shippingFee);
                       vm.order.goodsPrice = parseFloat(r.goods.retailPrice) * parseFloat(vm.ordergoods.number);*/
                    vm.ordergoods.goodsname = r.goods.name;
                    vm.ordergoods.goodsId = r.goods.id;
                    vm.ordergoods.goodsName = r.goods.name;
                    vm.ordergoods.goodsSn = r.goods.goodsSn;
                    vm.retailPrice = r.goods.retailPrice;
                    //vm.ordergoods.retailPrice = r.goods.retailPrice;
                    //vm.ordergoods.marketPrice = parseFloat(r.goods.marketPrice) * parseFloat(vm.ordergoods.number);;
                    //vm.ordergoods.retailPrice = vm.order.goodsPrice;
                    vm.ordergoods.listPicUrl = r.goods.listPicUrl;
                    vm.getProductsByGoodsid(r.goods.id);
                }
            });
        },
        //删除商品
        deleteOrdergoods: function (productid) {
            for (var i = 0; i < vm.ordergoodss.length; i++) {
                if (vm.ordergoodss[i].productId == productid) {
                    vm.order.actualPrice -= parseFloat(vm.ordergoodss[i].retailPrice) * parseFloat(vm.ordergoodss[i].number);
                    if (vm.order.actualPrice < 0)
                        vm.order.actualPrice = 0;
                    vm.order.orderPrice -= parseFloat(vm.ordergoodss[i].retailPrice) * parseFloat(vm.ordergoodss[i].number);
                    vm.order.goodsPrice -= parseFloat(vm.ordergoodss[i].marketPrice) * parseFloat(vm.ordergoodss[i].number);
                    vm.ordergoodss.splice(i, 1);
                }
            }
            $("#ordergoodsGrid").jqGrid("clearGridData");
            for (var i = 0; i < vm.ordergoodss.length; i++) {
                $("#ordergoodsGrid").jqGrid('addRowData', i + 1, vm.ordergoodss[i]);
            }
        },
        //添加商品
        addgoods: function () {
            if (vm.ordergoods.goodsName == '')
                alert("请先查询商品");
            if (vm.order.product == null)
                alert("请选择商品规格");
            vm.ordergoods.productId = vm.order.product.id;
            //如果单价被修改则按修改单价计算
            if (vm.retailPrice == vm.ordergoods.retailPrice) {
                vm.ordergoods.retailPrice = vm.order.product.retailPrice;
                vm.order.actualPrice += parseFloat(vm.order.product.retailPrice) * parseFloat(vm.ordergoods.number);
            } else {
                vm.ordergoods.retailPrice = vm.retailPrice;
                vm.order.actualPrice += parseFloat(vm.retailPrice) * parseFloat(vm.ordergoods.number);
            }

            vm.ordergoods.marketPrice = vm.order.product.marketPrice;
            vm.ordergoods.goodsSpecifitionNameValue = vm.order.product.specificationValue;
            vm.ordergoods.goodsSpecifitionIds = vm.order.product.goodsSpecificationIds;

            vm.order.orderPrice += parseFloat(vm.order.product.retailPrice) * parseFloat(vm.ordergoods.number);
            vm.order.goodsPrice += parseFloat(vm.order.product.marketPrice) * parseFloat(vm.ordergoods.number);

            var cloneordergoods = {};

            for (var attr in vm.ordergoods) {
                cloneordergoods[attr] = vm.ordergoods[attr];
            }
            if (vm.ordergoodss.length > 0) {
                $("#ordergoodsGrid").jqGrid("clearGridData");
                var isadd = 1;
                for (var i = 0; i < vm.ordergoodss.length; i++) {
                    if (vm.ordergoodss[i].productId == cloneordergoods.productId) {
                        isadd = 0
                        vm.ordergoodss[i].number += cloneordergoods.number;
                    }
                }
                if (isadd == 1)
                    vm.ordergoodss.push(cloneordergoods);

                for (var i = 0; i < vm.ordergoodss.length; i++) {
                    $("#ordergoodsGrid").jqGrid('addRowData', i + 1, vm.ordergoodss[i]);
                }
            } else {
                vm.ordergoodss.push(cloneordergoods);
                $("#ordergoodsGrid").jqGrid('addRowData', vm.ordergoodss.length + 1, cloneordergoods);
            }
        },
        //获取商品绑定
        getGoodss: function () {

            Ajax.request({
                url: "../goods/queryAll/",
                async: true,
                successCallback: function (r) {
                    vm.goodss = r.list;
                }
            });
        },
        //获取商品规格
        getProductsByGoodsid: function (goodsid) {

            Ajax.request({
                url: "../product/queryByGoodsId/" + goodsid,
                async: true,
                successCallback: function (r) {
                    vm.products = r.list;
                }
            });
        },

        sendGoods: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }

            // openWindow({
            //     type: 2,
            //     title: '发货管理',
            //     content: '..//ordershipping.html?orderid=' + id
            // })
            vm.showList = false;
            vm.title = "发货";
            Ajax.request({
                url: "../order/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.order = r.order;
                }
            });
        },
        cancelOrder: function (rowId) {
            var orderobj = {};
            orderobj.id = rowId;

            orderobj.orderStatus = 101;
            Ajax.request({
                type: "POST",
                url: "../order/update",
                contentType: "application/json",
                params: JSON.stringify(orderobj),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        confirm: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            confirm('确定收货？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../order/confirm",
                    contentType: "application/json",
                    params: JSON.stringify(id),
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        lookConfirm: function (rowId) {
            vm.showconfirm = true;
            vm.showadd = false;
            vm.showList = false;
            vm.detail = false;
            vm.title = "确认收款";
            vm.order.id = rowId;
            let url = '../ordergoods/list?orderId=' + rowId;
            let page = $("#ordergoodsLookConfirmGrid").jqGrid('getGridParam', 'page');
            $("#ordergoodsLookConfirmGrid").jqGrid('setGridParam', {
                url: url,
                datatype: "json",
                page: page
            }).trigger("reloadGrid");

            Ajax.request({
                url: "../order/info/" + rowId,
                async: true,
                successCallback: function (r) {
                    vm.order = r.order;
                }
            });

        },
        confirmmoney: function (event) {
            vm.order.orderStatus = 201;
            vm.order.payStatus = 2;

            Ajax.request({
                type: "POST",
                url: "../order/update",
                contentType: "application/json",
                params: JSON.stringify(vm.order),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        saveOrUpdate: function (event) {
            if (vm.order.id == null) {
                Ajax.request({
                    type: "POST",
                    url: "../order/save",
                    contentType: "application/json",
                    async: false,
                    params: JSON.stringify(vm.order),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            } else {
                Ajax.request({
                    type: "POST",
                    url: "../order/update",
                    contentType: "application/json",
                    async: false,
                    params: JSON.stringify(vm.order),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            }


        },
        saveSend: function (event) {
            if (vm.order.payStatus != '2') {
                alert("该订单未付款");
                return;
            }
            if (vm.order.logisticsno == null) {
                alert("请填写物流单号");
                return;
            }
            if (vm.logistics.name == null) {
                alert("请填写物流名称");
                return;
            }
            if (vm.logistics.statu == null) {
                vm.logistics.statu = 1;
            }
            vm.logistics.orderno = vm.order.orderNo;
            vm.logistics.pid = vm.order.productId;
            vm.logistics.pname = vm.order.productName;
            vm.logistics.num = vm.order.number;
            vm.logistics.code = vm.order.code;
            vm.logistics.userId = vm.order.userId;
            vm.logistics.userName = vm.order.userName;
            vm.logistics.phone = vm.order.userPhone;
            vm.logistics.logisticsno = vm.order.logisticsno;
            vm.logistics.type = 1;
            vm.logistics.receiveUser = vm.order.receiveUser;
            vm.logistics.orderDate = vm.order.createDate;
            vm.logistics.remark = vm.order.remark;
            Ajax.request({
                type: "POST",
                url: "../logistics/save",
                contentType: "application/json",
                params: JSON.stringify(vm.logistics),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.detail = false;
            vm.showadd = false;
            vm.showconfirm = false;
            vm.showselect = false;
            console.log(vm.q.date)
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'orderNo': vm.q.orderNo,
                    'userPhone': vm.q.userPhone,
                    'payStatus': vm.q.payStatus,
                    'status': vm.q.status,
                    'payWay': vm.q.payWay,
                    'merchantId':vm.q.merchantId,
                    'start':vm.q.start==''?'':new Date(vm.q.start).dateFormat("yyyy-MM-dd hh:mm:ss"),
                    'end':vm.q.end==''?'':new Date(vm.q.end).dateFormat("yyyy-MM-dd hh:mm:ss")
                },
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        lookDetail: function (rowId) { //第三步：定义编辑操作
            vm.detail = true;
            vm.showadd = false;
            vm.title = "详情";

            let url = '../ordergoods/list?orderId=' + rowId;
            let page = $("#ordergoodsLookGrid").jqGrid('getGridParam', 'page');
            $("#ordergoodsLookGrid").jqGrid('setGridParam', {
                url: url,
                datatype: "json",
                page: page
            }).trigger("reloadGrid");
            Ajax.request({
                url: "../order/info/" + rowId,
                async: true,
                successCallback: function (r) {
                    vm.order = r.order;
                }
            });
        },
        printDetail: function (rowId) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-print"></i>打印票据',
                content: ['orderPrint.html?orderId=' + id]
            })
        },
        reloadSearch: function () {
            vm.q = {
                orderNo: '',
                userPhone: '',
                payStatus: '',
                status: '',
                payWay:'',
                date:'',
                merchantId:'',
                start:'',
                end:''
            }
            vm.reload();
        },
    },
    created: function () {
        let vue = this;
    }
});